package com.wy.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wy.common.Result;
import com.wy.dto.GoodsInfoDto;
import com.wy.entity.GoodsDeposit;
import com.wy.service.GoodsDepositService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;

/**
 * @Author:王渝
 * @Date: 2023/1/2  15:20
 * @Version 1.0
 */
@RestController
@Slf4j
@RequestMapping("/deposit")
public class GoodsDepositController {

    @Autowired
    private GoodsDepositService goodsDepositService;

    /**
     * 缴纳保证金
     * @param goodsInfoDto
     * @return
     */
    @RequestMapping("/pay")
    public Result<String> payDeposit(@RequestBody GoodsInfoDto goodsInfoDto){
        if(goodsInfoDto.getUserId().equals(goodsInfoDto.getBuyerUserId())){
            return Result.error("不能参与自己的拍卖");
        }

        LocalDateTime now = LocalDateTime.now();
        if(now.isBefore(goodsInfoDto.getStartingTime())){
            return Result.error("拍卖还没开始");
        }

        if(now.isAfter(goodsInfoDto.getEndTime())){
            return Result.error("拍卖已经结束");
        }

        LambdaQueryWrapper<GoodsDeposit> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(GoodsDeposit::getUserId,goodsInfoDto.getBuyerUserId())
                .eq(GoodsDeposit::getGoodsId,goodsInfoDto.getGoodsId());
        //SELECT COUNT( * ) FROM goods_deposit WHERE (user_id = ? AND goods_id = ?)
        int count = goodsDepositService.count(lambdaQueryWrapper);
        if(count > 0){
            return Result.error("你已经缴纳过保证金了");
        }
        GoodsDeposit goodsDeposit = new GoodsDeposit();
        goodsDeposit.setUserId(goodsInfoDto.getBuyerUserId());
        goodsDeposit.setAmount(goodsInfoDto.getDeposit());
        goodsDeposit.setGoodsId(goodsInfoDto.getGoodsId());

        boolean success = goodsDepositService.payDeposit(goodsDeposit);
        if(success){
            return Result.success("缴纳成功");
        }
        return Result.error("余额不足");
    }

}
